//
//  MyBankManagerViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/14.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
class MyBankManagerViewController: UIViewController {

    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            
            _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
            _tableView.separatorInset = UIEdgeInsets.zero
            _tableView.separatorStyle = .singleLine
            _tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            regClass(_tableView, cell: UITableViewCell.self)
            
            return _tableView
        }
    }
    
    var defaultModel: BankCardModel? //选中的model,即checkMark的cell
    
    var bankCardModel: [BankCardModel]?
    var selectionHandler:(() -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "选择银行卡"
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.bottom.equalTo(self.view)
        }
        
        let header = MJRefreshNormalHeader {
            self.getData()
        }
        header?.stateLabel.isHidden = true
        self.tableView.mj_header = header
        
        self.tableView.mj_header.beginRefreshing()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        WWProgressHUD.dismiss()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getData()
    }
    func getData() {
        BankCardModel.getBankCard { (response) in
            if response.success {
                self.bankCardModel = response.value
                
                if let models = self.bankCardModel {
                    for item in models {
                        if item.isDefault {
                            self.defaultModel = item
                        }
                    }
                }
                self.tableView.reloadData()
            }
            else {
                WWError(response.message)
            }
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    @objc func doAddAction() {
        let vc = BankCardAddController.init(.bankChoice)
        vc.addFinishHandler = {[unowned self] in
            self.tableView.mj_header.beginRefreshing()
            
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }

}
extension MyBankManagerViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.bankCardModel?.count ?? 0
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell.init(style: .value2, reuseIdentifier: "\(UITableViewCell.self)")
        
        cell.textLabel?.textColor = UIColor.black
        cell.textLabel?.font = wwFont_Medium(15)
        cell.detailTextLabel?.textColor = UIColor.mg_lightGray
        cell.detailTextLabel?.font = wwFont_Medium(15)
        cell.textLabel?.textAlignment = .left
        cell.selectionStyle = .none
        if let model = self.bankCardModel?[indexPath.row] {
            cell.textLabel?.text = model.bankName
            
            let bankAccount = model.salaryCardBankAccount
            if bankAccount != nil {
                cell.detailTextLabel?.text = "尾号" + lastFourNumbers(bankAccount!)
            }
            else {
                cell.detailTextLabel?.text = "数据异常"
            }
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     //  self.navigationController?.popViewController(animated: true)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if self.bankCardModel != nil {
            let view = UIView()
            
            let button = UIButton()
            button.backgroundColor = UIColor.mg_blue
            button.addTarget(self, action: #selector(doAddAction), for: .touchUpInside)
            button.setTitle("添加银行卡", for: .normal)
            button.titleLabel?.font = wwFont_Medium(17)
            button.layer.shadowColor = UIColor.black.cgColor
            button.layer.shadowOffset = CGSize(width: 1, height: 1)
            button.layer.shadowOpacity = 0.3
            button.layer.cornerRadius = 6
            view.addSubview(button)
            button.snp.makeConstraints { (make) in
                make.center.equalTo(view)
                make.width.equalTo(200)
                make.height.equalTo(40)
            }
            
            return view
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.bankCardModel != nil {
            return 100
        }
        return 0.00001
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    /***左滑删除设置***/
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    //点击删除时调用
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            guard let model = self.bankCardModel?[indexPath.row] else {
                return
            }
            guard let cardId = model.bankCardId else {
                return
            }
            WWBeginLoadingWithStatus("开始删除")
            BankCardModel.removeBankCard(cardId, completionHandler: { (response) in
                if response.success {
                    self.bankCardModel?.remove(at: indexPath.row)
                    tableView.beginUpdates()
                    tableView.deleteRows(at: [indexPath], with: .automatic)
                    tableView.endUpdates()
                    
                    if self.selectionHandler != nil {
                        self.selectionHandler!()
                    }
                    
                    WWSuccess("删除成功")
                }
                else {
                    WWError(response.message)
                }
            })
            
        }
    }
}

